package org.ofbiz.wvtools.word;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Locale;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerWordTemplateUtils {

    private static String defaultCharacter = "UTF-8";
    private static Configuration cfg;

    public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");

     //private static String wordTemplatePath = OFBIZ_HOME +"/applications/autoconfig/config/word-template";

    private static String wordTemplatePath = "D:/workspace/frame_sever/applications/wvtools/config/word-template/";

    /**
     * 
     * @param outFilePath 输出文件路径
     * @param myTemplate  模板文件名 。路径为wordTemplatePath
     * @param map         传入参数
     * @return
     */
    public static String processWordTemplate(String outFilePath, String myTemplate, Map<String, Object> map) {
	String result = null;
	try {
	    if (myTemplate.contains(wordTemplatePath)) {
		myTemplate = myTemplate.replace(wordTemplatePath, "");
	    }
	    FreemarkerWordTemplateUtils obj = new FreemarkerWordTemplateUtils();
	    obj.init();
	    Template t = obj.getCfg().getTemplate(myTemplate, "UTF-8");

	    // 输出文档路径及名称
	    File outFile = new File(outFilePath);

	    // BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
	    // FileOutputStream(outFile), "utf-8"), 10240);
	    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
	    t.process(map, out);
	    out.close();

	} catch (Exception e) {
	    e.printStackTrace();
	}
	return result;
    } 

    @SuppressWarnings("deprecation")
    public void init() throws IOException {
	cfg = new Configuration();
	cfg.setDefaultEncoding(defaultCharacter);
	cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
	cfg.setDirectoryForTemplateLoading(new File(wordTemplatePath));
	cfg.setEncoding(Locale.getDefault(), defaultCharacter);
    }

    public Configuration getCfg() {
	return cfg;
    }

}